import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/file_upload/file_upload_tool.dart';
import 'package:tiktokadult/tools_base/loading/loading_alert_widget.dart';

class MineFeedbackLogic extends GetxController {
  /// 问题描述
  TextEditingController inputFeedback = TextEditingController();

  /// 区域
  TextEditingController areaFeedback = TextEditingController();

  /// 设备
  TextEditingController deviceFeedback = TextEditingController();

  /// 网络运营商
  TextEditingController netFeedback = TextEditingController();

  ///联系方式
  TextEditingController contactFeedback = TextEditingController();

  ///封面本地地址
  List<String> _localPicList = [];

  String _questionCategory = '';

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onInit() {
    super.onInit();
  }

  /// 主要问题
  updateQuestionCategory(String category) => _questionCategory = category;

  /// 资源图片变化
  updateQuestionImages(List<String> images) => _localPicList = images;

  Future<void> onSubmit() async {
    if (inputFeedback.text.isEmpty) {
      showToast("请填写问题描述");
      return;
    }

    LoadingAlertWidget.show();
    try {
      List<String> imageArr = [];
      if (_localPicList.isNotEmpty) {
        LoadingAlertWidget.showExchangeTitle("正在上传图片...");
        var uploadImgArr = await FileUpLoadTool().uploadImageList(_localPicList, proCallback: (tIndex, tAll, proCount, totalCount) {
          LoadingAlertWidget.showExchangeTitle("正在上传图片${(100 * (proCount / totalCount / tAll + tIndex / tAll)).toStringAsFixed(1)}%");
        });

        if (uploadImgArr?.isNotEmpty == true) {
          imageArr = uploadImgArr!.map((e) => e.coverImg ?? "").toList();
        }
        LoadingAlertWidget.showExchangeTitle("正在更新数据...");

        debugLog('上传完成');
      }
      FocusScope.of(Get.context!).unfocus();
      final success = await MineService.feedback(inputFeedback.text,
          location: areaFeedback.text,
          device: deviceFeedback.text,
          carrier: netFeedback.text,
          img: imageArr,
          fType: _questionCategory,
          contact: contactFeedback.text);
      if (success) {
        Get.back();
        showToast('提交成功');
      } else {
        showToast('提交失败');
      }
    } on DioException catch (e) {
      showToast(e.message ?? '');
    } catch (e) {
      showToast(e.toString());
    } finally {
      LoadingAlertWidget.cancel();
    }
  }
}
